import { createRouter, createWebHistory } from 'vue-router'
import consoleview from '../views/console.vue'
import { $doLogin } from '@/api/apis/aa';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '',
      alias: ['/index', '/home', '/default', '/'],
      name: 'default',
      meta: {
        title: 'portal首页'
      },
      component: () => import('../views/portal.vue')
    },
    {
      path: '/login',
      name: 'login',
      meta: {
        title: '登录'
      },
      component: () => import('../views/login.vue')
    },
    {
      path: '/admin',
      name: 'admin',
      component: consoleview,
      children: [{
        path: '',
        name: 'home',
        meta: {
          title: '管理平台首页'
        },
        component: () => import('../components/admin/home/home.vue')
      }]
    },
    {
      path: '/:pathMatch(.*)*',
      name: '404',
      meta: {
        title: '404'
      },
      component: () => import('../views/error404.vue')
    }
  ]
});

router.beforeEach((to, from, next) => {
  // 用户已经登录，但是请求登录地址直接进入控制台界面
  let token = sessionStorage.getItem("token");
  if (to.path.substring(0, 6) == "/login" && token) {
    router.push("/admin")
  }
  // 自动登录功能
  if (to.path.substring(0, 6) == "/login") {
    let aa = localStorage.getItem("aa")
    if (aa) {
      let { username, password, remember } = JSON.parse(aa)
      if (remember) {
        $doLogin({ username, password, remember }).then((result) => {
          if (result) {
            router.push("/admin")
          }
        })
      }
    }
  }
  if (!token && to.path.substring(0, 8) == "/admin") {
    next("/login");
  } {
    next();
  }

});

router.afterEach((to, from) => {
  document.title = to.meta.title;

});


export default router;
